#!/bin/sh
#
# Start the Flexhouse platform.
#
# The script tries to determine the right conf/platform.xml file, if that file
# does not exist already. This behaviour can be overridden by specifying the
# platform.xml file as the second parameter.  The first parameter can be used to
# specify the hostname that should be used for finding the platform.xml file.
# When the second option for a specific platform.xml file is given, this
# parameter is ignored, though.
#
# The option --service (as first option!) can be used to prepare the script for
# usage as a service; right now, this only means that output is redirected to
# flexhouse-stdout.log. The other options can still be used; they have to be put
# after the --service option, though.

#show UI always locally
export DISPLAY=":0.0"

SERVICE=0
if test "$1" = "--service"; then
  shift
  SERVICE=1
  exec >> flexhouse-stdout-$(date +"%Y%m%d").log 2>&1
fi

if test -z "$1"; then
  HOSTNAME=`hostname`
else
  HOSTNAME=$1
fi

PLATFORM_XML="conf/platform.xml"
if test -e "$2"; then
  PLATFORM_XML="$2"
fi


BASE=$(dirname "$0")
BASE=$(cd "$BASE" && pwd)
CP="$BASE/bin/"
for JAR in $BASE/lib/*.jar; do
  CP="$CP:$JAR"
done
LP=.:/usr/lib/:/usr/lib/jni/

# autogenerate platform.xml (platform config file) by linking
# to platform.xml.<hostname>

if test ! -e "$PLATFORM_XML"; then
  if test -e conf/platform.xml.$HOSTNAME; then
    ( cd conf && ln -s platform.xml.$HOSTNAME platform.xml)
  else
    echo "Could not find a platform.xml.$HOSTNAME file!"
  fi
fi

if test $SERVICE != 0; then
  if test -x "/usr/sbin/rotatelogs"; then
    exec java $JAVA_ARGS -Djava.library.path="$LP"/ -classpath "$CP" -Dbase="$BASE" risoe.syslab.fhnew.core.FlexhouseCore "$PLATFORM_XML" 2>&1 | /usr/sbin/rotatelogs flexhouse-stdout-%Y%m%d.log 86400
  elif test -x "/usr/sbin/rotatelogs2"; then
    exec java $JAVA_ARGS -Djava.library.path="$LP" -classpath "$CP" -Dbase="$BASE" risoe.syslab.fhnew.core.FlexhouseCore "$PLATFORM_XML" 2>&1 | /usr/sbin/rotatelogs2 flexhouse-stdout-%Y%m%d.log 86400
  else
    exec java $JAVA_ARGS -Djava.library.path="$LP" -classpath "$CP" -Dbase="$BASE" risoe.syslab.fhnew.core.FlexhouseCore "$PLATFORM_XML">> flexhouse-stdout-$(date +"%Y%m%d").log 2>&1
  fi
else
  exec java $JAVA_ARGS -Djava.library.path="$LP" -classpath "$CP" -Dbase="$BASE" risoe.syslab.fhnew.core.FlexhouseCore "$PLATFORM_XML"
fi

